package com.example.demo.admin.core.shiro;/**
 * Created by kete on 2017-10-20.
 */

import com.example.demo.admin.core.shiro.factory.Ishiro;
import com.example.demo.admin.core.shiro.factory.ShiroFactory;
import com.example.demo.common.persistence.model.User;
import com.example.demo.common.vo.ShiroUser;
import com.example.demo.core.support.StrKit;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 作者：kete
 * 创建时间：2017-10-20 16:24
 * 功能描述：
 * 版本：
 */
public class ShiroDbRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Ishiro ishiro = ShiroFactory.me();

        ShiroUser shiroUser = (ShiroUser)principalCollection.getPrimaryPrincipal();

        List<Integer> roleIds = shiroUser.getRoleList();

        Set<String> permissionSet = new HashSet<>();
        Set<String> roleNameSet = new HashSet<>();

        roleIds.forEach(roleId->{
            //角色名
            roleNameSet.add(ishiro.findRoleNameByRoleId(roleId));

            //请求路径
            ishiro.findPermissionsByRoleId(roleId).forEach(permissionUrl->{
                if(StrKit.isNotEmpty(permissionUrl))
                    permissionSet.add(permissionUrl);
            });
        });

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roleNameSet);
        info.setStringPermissions(permissionSet);

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        Ishiro ishiro = ShiroFactory.me();
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        User user = ishiro.user(token.getUsername());
        ShiroUser shiroUser = ishiro.shiroUser(user);

        SimpleAuthenticationInfo info = ishiro.info(shiroUser, user, super.getName());

        return info;
    }

    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        HashedCredentialsMatcher md5CredentialsMatcher = new HashedCredentialsMatcher();
        md5CredentialsMatcher.setHashAlgorithmName(ShiroKit.hashAlgorithmName);
        md5CredentialsMatcher.setHashIterations(ShiroKit.hashIterations);

        super.setCredentialsMatcher(md5CredentialsMatcher);
    }
}
